<?php

namespace App\Http\Controllers;

use App\Exceptions\BusinessException;
use App\Http\Traits\ApiResponse;
use App\Services\ResponseCode;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class GeneralFileUpload extends Controller
{
    use ApiResponse;

    /**
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     * @throws BusinessException
     */
    public function avatar(Request $request)
    {
        $validMIMETypes = [
            'image/png',
            'image/jpeg',
            'image/gif',
            'image/vnd.microsoft.icon',
            'image/bmp',
            'image/svg+xml',
            'image/tiff',
            'image/webp',
        ];

        $file = $request->file(__FUNCTION__);

        if($file === null){
            throw new BusinessException('upload file not exists!', ResponseCode::UPLOAD_FILE_NOT_EXISTS);
        }

        if (!in_array($file->getMimeType(), $validMIMETypes)) {
            throw new BusinessException('invalid file MIME type:' . $file->getMimeType(), ResponseCode::INVALID_FILE_MIME_TYPE);
        }

        $path = $file->store('public/' . __FUNCTION__);
        return $this->success('success', [
            'url' => $request->getHost() . Storage::url($path),
            'relative_path' => Storage::url($path),
        ]);
    }
}
